#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

using namespace std;
using namespace ThreadMoudle;
// 客户端在未来一定要知道服务器的ip和端口号
//  ./udp_client server-ip server-port
//  ./udp_client 127.0.0.1    8888
//        0          1          2
int InitClient()
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // 创建套接字
    if (sockfd < 0)
    {
        cerr << "create sockfd error" << endl;
        exit(1);
    }
    return sockfd;
}
void RecvMessage(int sockfd, const string &name)
{
    while(true)
    {
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        char buffer[1024];
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &len); // 服务器只有一个不做处理
        if (m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
        else
        {
            std::cout << "recvfrom error" << std::endl;
            break;
        }
    }
}
void SendMessage(int sockfd, string serverip, uint16_t serverport, const string &name)
{
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    std::string cli_profix = name + "# "; // sender-thread# 你好
    while (true)
    {
        std::string line;
        std::cout << cli_profix;
        std::getline(std::cin, line);
        int n = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n <= 0)
            break;
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "Usage:" << argv[0] << "server-ip server-port" << endl;
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);
    int sockfd = InitClient(); // 初始化客户端

    Thread recver("recver-thread", std::bind(&RecvMessage, sockfd, placeholders::_1));//两个线程一个收一个发
    Thread sender("sender-thread", std::bind(&SendMessage, sockfd, serverip, serverport, std::placeholders::_1));

    recver.Start();
    sender.Start();

    recver.Join();
    sender.Join();

    // client的端口号，一般不让用户自己设定，而是让client OS随机选择？怎么选择，什么时候选择呢？
    // client 需要 bind它自己的IP和端口， 但是client 不需要 “显示” bind它自己的IP和端口，
    // client 在首次向服务器发送数据的时候，OS会自动给client bind它自己的IP和端口

    ::close(sockfd);
    return 0;
}